<?php

namespace App\Http\Controllers\Api\v2;

use App\Http\Controllers\ApiController;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;

class LoginController extends ApiController
{
    //
    public function index()
    {
        $account = $this->request->input('account');
        $password = $this->request->input('password');

        if ($this->check($account, $password)) {
            $user = Auth::user();
            $api_token = Str::random(60);
            $user->update(['api_token'=>$api_token]);
            $user->avatar = avatar($user->uid);
            $user->logs()->create([
                'ip'=>$this->request->getClientIp(),
                'operate'=>'login',
                'created_at'=>time(),
                'src'=>'app'
            ]);
            return ajaxReturn([
                'user'=>$user,
                'api_token'=>$api_token
            ]);
        }

        return ajaxError(401, '账号或密码错误');
    }

    private function check($account, $password){
        if (Auth::guard()->attempt(['mobile'=>$account, 'password'=>$password])) {
            return true;
        }

        if (Auth::guard()->attempt(['email'=>$account, 'password'=>$password])) {
            return true;
        }

        if (Auth::guard()->attempt(['username'=>$account, 'password'=>$password])) {
            return true;
        }

        return false;
    }
}
